package controllers

import (
	"net/http"
	"fmt"
	"go-scripts/common"
	"encoding/json"
	"go-scripts/handler"
)

var indexController *IndexController
var logger *common.Log = common.GetLogger()

type IndexController struct {

}

func (i *IndexController) Index(app *handler.Global) {
	fmt.Fprintf(app.ResponseWriter, "%s\n", "hello, world")
}

func GetIndexController() *IndexController {
	if indexController != nil {
		return indexController
	}
	indexController = new(IndexController)
	return indexController
}

func HandleError(w http.ResponseWriter, r *http.Request, message string, code int)  {
	w.WriteHeader(code)
	SendJson(w, map[string]interface{}{
		"msg": message,
		"code": code,
	})
	logger.Error(common.PrintURLMiddleWare(r), code, message)
}

func SendJson(w http.ResponseWriter, v interface{})  {
	vJson, err := json.Marshal(v)
	if err != nil {
		w.Write([]byte("error json"))
		return
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Write(vJson)
}